﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using PublicClass.Entity;
using S.RBAC.Api.Application.Command.StaffCommand;
using S.RBAC.Domain.Dto;
using S.RBAC.Infrastructure.Interface;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace S.RBAC.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class StaffController : ControllerBase
    {
        protected readonly IMediator _mediator;
        protected readonly IConfiguration _configuration;

        public StaffController(IMediator mediator, IConfiguration configuration)
        {
            _mediator = mediator;
            _configuration = configuration;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<OutputLoginDto> Login(StaffLoginCommand command)
        {
            var info = await _mediator.Send(command);

            if(info.StaffId != null)
            {
                info.Token = JwtNewString(info.StaffId.ToString());
                return info;
            }

            return info;
        }

        /// <summary>
        /// 生成JWT
        /// </summary>
        /// <param name="StaffId"></param>
        /// <returns></returns>
        private string JwtNewString(string StaffId)
        {
            //生成JWT
            //Header，选择签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;

            //PayLoad,存放用户信息，下面放一个用户Id
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,StaffId),
                //new Claim(ClaimTypes.Role,"admin"),
                //new Claim(ClaimTypes.UserData,"测试")
            };

            //Signarue
            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            //使用非对称算法对私要进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(
                issuer: _configuration["Authentication:Issuer"],        //发布者
                audience: _configuration["Authentication:Audience"],    //接收者
                claims: claims,                                          //存放的用户信息
                notBefore: DateTime.UtcNow,                              //发布时间
                expires: DateTime.UtcNow.AddDays(1),                     //有效期设置为1天
                signingCredentials                                      //数字签名
                );
            //生成字符串Token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);

            return TokenStr;
        }

        /// <summary>
        /// 员工添加
        /// </summary>
        /// <param name="command">员工信息表单</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddStaff(StaffCreateCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file uploaded.");
            }

            //保存路径和文件名
            string saveFile = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Pic", file.FileName);

            using (FileStream fs = new(saveFile, FileMode.Create))
            {
                await file.CopyToAsync(fs);
                fs.Flush();
            }

            //返回前端图片名称
            return Ok(file.FileName);
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<int> DelStaff([FromQuery]StaffDeleteCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 员工修改
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdStaff(StaffUpdateCommand command)
        {
            return await _mediator.Send(command);
        }
    }
}
